package com.voltbarn.vbsensors;

import java.util.List;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Handler;
import android.util.Log;
import android.view.View;


public final class AndroidSensors extends View implements SensorEventListener{
	
	private static final String TAG = AndroidSensors.class.getSimpleName();
	private Handler handler;
	private float temperatureF = -99;

	public AndroidSensors(Context context) {
		super(context);
		//init();
		attachToSensor();
	}
	
	public float getTemp() {
		return temperatureF;
	}
	
	private SensorManager getSensorManager() {
		return (SensorManager) getContext().getSystemService(Context.SENSOR_SERVICE);		
	}
	
	private void attachToSensor() {
		SensorManager sensorManager = getSensorManager();
		
		List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_TEMPERATURE);
		if (sensors.size() > 0) {
			Sensor sensor = sensors.get(0);
			sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_FASTEST, handler);
		} else {
			Log.e(TAG, "No temperature sensor found");
		}		
	}
	
	private void detachFromSensor() {
		SensorManager sensorManager = getSensorManager();
		sensorManager.unregisterListener(this);
	}
	
	@Override
	public void onSensorChanged(SensorEvent sensorEvent) {
		if (sensorEvent.values.length > 0) {
			float temperatureC = sensorEvent.values[0];
			//Log.i(TAG, "*** Temperature: " + temperatureC);
			
			temperatureF = (9.0f / 5.0f) * temperatureC + 32.0f;
			//setHandTarget(temperatureF);
		} else {
			Log.w(TAG, "Empty sensor event received");
		}
	}

	@Override
	public void onAccuracyChanged(Sensor arg0, int arg1) {
		// TODO Auto-generated method stub
		
	}
}
